
<template>
  <dialog-normal
    ref="dialog-active"
    :dialog-prop="{
      title: title,
      height: '55vh',
      width: '60%',
      submit: '确定',
      close: '取消'
    }"
    @normal-submit="submitDialog('active', currentItem)"
    >
    <template #dialog-content v-if="$refs[`dialog-active`] && $refs[`dialog-active`].showDialog">
      <el-form
        class="form-content"
        ref="active-form" label-position="left"
        :model="currentItem"
        label-width="120px">
        <div class="form-title">服务信息</div>
        <el-form-item class="form-content-item" label="服务类型">
          <el-select v-model="currentItem.serveTypeTwo" placeholder="请选择" @change="activeTypeChange">
            <!-- <el-option label="内部卡券发行" :value="1"></el-option> -->
            <!-- <el-option :value="0" label="服务"></el-option>
            <el-option :value="1" label="外部卡券"></el-option> -->
            <el-option v-for="serveType in serveTypeList" :key="serveType.dictCode" 
            :value="serveType.id" :label="serveType.serveType"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-content-item" label="活动名称">
          <el-input v-model="currentItem.activityName" placeholder="洗车活动优惠"></el-input>
        </el-form-item>
        <el-form-item class="form-content-item" label="接收单位">
          <el-input v-model="currentItem.acceptingUnit" placeholder="太平洋保险"></el-input>
        </el-form-item>
        <el-form-item label="服务内容" v-if="boo.flashPackModel">
          <package-model :config="packageModel" v-model="currentItem.serveTypeIds" 
          :params="currentItem" @change="packageChange"/>
        </el-form-item>
        <el-form-item class="form-content-item" label="有效期">
          <time-date-select v-model="currentItem" @change="dataChange"/>
        </el-form-item>
        <el-form-item class="form-content-item" label="生成卡券">
          <div class="num-form-content flex-normal">
            <span class="num-desc-txt">生成</span>
            <el-input class="num-form" v-model="currentItem.number" placeholder="输入数量"></el-input>
            <span class="num-desc-txt">张卡券</span>
            <div class="num-btn flex-center">
              <el-button type="text" class="btn-txt" @click="generateCardRoll" :loading="boo.generateCardRoll">生成卡券</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="券码情况">
          <ticket-model :arr="ticketArr" :card-list="generateCardList" 
          @change="ticketChange" :active-id="currentItem.id"/>
        </el-form-item>
        <el-form-item label="商家列表">
          <store-list-model :shop-list="shopList" v-model="currentItem.suitShopIds"/>
        </el-form-item>
        <el-form-item class="form-content-item" label="活动描述">
          <el-input type="textarea" :rows="3" v-model="currentItem.remarks" placeholder="请输入活动描述"></el-input>
        </el-form-item>
      </el-form>
    </template>
  </dialog-normal>
</template>

<script>
import {getNowDate, getPassYear} from '@/utils/tools.js'
import {getShopListDict} from "@/api/common/index.js";
import {
  addActivity, editActivity, getActiveFiles, generateCardRoll, getActivityDetail
} from "@/api/activeManage/active";
import {
  getServeList
} from "@/api/activeManage/serve";
import {
  getServeTypeDict
} from "@/api/common/index";
export default {
  props: {
    value: {
      type: Boolean,
      default: () => false
    },
  },
  components: {
    "dialog-normal": () => import("@/rhComponents/dialog/normal-dialog"),
    "package-model": () => import("@/views/components/active/package-model"),
    "store-list-model": () => import("@/views/components/active/store-list-model"),
    "ticket-model": () => import("@/views/components/active/ticket-model"),
    "time-date-select": () => import("@/rhComponents/time-date-select/index"),
  },
  data() {
    return {
      serveTypeArr: [
        {"dictLabel": "服务", "dictCode": '0'},
        // {"dictLabel": "外部卡券", "dictCode": '1'},
      ],
      title: '',
      boo: {
        generateCardRoll: false,
        flashPackModel: false,
      },
      generateCardList: [], //新生成的卡券列表
      shopList: [], //商家列表
      serveTypeList: [], //服务类型列表
      currentItem: {},
      activeFiles: {},
      // 服务内容配置
      packageModel: {
        tabs: [
          {label: '官方服务', name: 'gffw', list: []}
        ],
        hasAction: false
      },
      ticketArr: ['库存券码']
    };
  },
  mounted(){
    this.queryServeTypeList()
  },
  methods: {
    validateNum(value){
      let reg = /^\d+$/
      if (!reg.test(value) || value == '0') return false
      return true
    },
    async queryServeTypeList(){
      let _self = this, isSuccess = false
      getServeTypeDict().then(res => {
        _self.serveTypeList = (res.data || []).filter(i => i.serveTypeTwo == '0')
        isSuccess = true
      })
      return isSuccess
    },
    async generateCardRoll(){
      let _self = this
      let params = {
        number: _self.currentItem.number
      }
      if(!params.number) return _self.$message.error('生成数量不能为空')
      if(!_self.validateNum(params.number)) return _self.$message.error('请填写正确的整数')
      _self.boo.generateCardRoll = true
      await generateCardRoll(params).then(res => {
        _self.generateCardList = res.data
      })
      _self.boo.generateCardRoll = false
    },
    // 获取官方服务列表
    async queryServeList(){
      let isSuccess = false, _self = this
      _self.boo.flashPackModel = false
      await getServeList({serveTypeTwo: _self.currentItem.serveTypeTwo}).then(res => {
        let tab = _self.packageModel.tabs.find(i => i.name == 'gffw')
        tab.list = res.rows.map(i => {
          return {
            id: i.id,
            inventoryNum: i.inventoryNum,
            serveImg: i.serveImg,
            serveName: i.serveName,
            serveDetails: i.serveDetails,
            price: i.price,
            writeOffFee: i.writeOffFee
          }
        })
        isSuccess = true
        _self.boo.flashPackModel = true
      })
      return isSuccess
    },
    // 获取商家列表
    async queryShopList(){
      let isSuccess = false, _self = this
      await getShopListDict().then(res => {
        _self.shopList = res.data.map(item => {
          return {
            id: item.id,
            shopName: item.shopName,
            shopAddress: item.shopAddress,
            isChecked: false
          }
        })
        isSuccess = true
      })
      return isSuccess
    },
    // 事件集合 -- 转发
    actionsMaps(ref, acion, row){
      let _self = this
      let actionsMap = () => {
        return new Map([
          [{ref: 'active', acion: 'add:show'}, async ()=>{
            _self.title = '新增自营商品'
            _self.ticketArr = ['库存券码']
            // await _self.queryServeTypeList()
            await _self.queryShopList()
            _self.currentItem = {
              startingTime: getNowDate(),
              endTime: getPassYear()
            }
            _self.$nextTick(() => {
              _self.$refs[`dialog-${ref}`].showDialog = true
            })
          }],
          [{ref: 'active', acion: 'edit:show'}, async ()=>{
            _self.title = '编辑自营商品'
            _self.ticketArr = ['库存券码', '已兑换', '已核销']
            _self.$set(row, 'isEdit', true)
            // await _self.queryServeTypeList()
            await _self.queryShopList()
            await getActivityDetail(row.id).then(async res => {
              _self.currentItem = res.data
              delete _self.currentItem['number']
              await _self.queryServeList()
              _self.$nextTick(() => {
                _self.$refs[`dialog-${ref}`].showDialog = true
              })
            })
            _self.$set(row, 'isEdit', false)
          }],
          [{ref: 'active', acion: 'view:show'}, async ()=>{
            _self.title = '查看自营商品'
            _self.ticketArr = ['库存券码', '已兑换', '已核销']
            _self.$set(row, 'isEdit', true)
            // await _self.queryServeTypeList()
            await _self.queryShopList()
            await getActivityDetail(row.id).then(async res => {
              _self.currentItem = res.data
              delete _self.currentItem['number']
              await _self.queryServeList()
              _self.$nextTick(() => {
                _self.$refs[`dialog-${ref}`].showDialog = true
              })
            })
            _self.$set(row, 'isEdit', false)
          }],
          [{ref: 'active', acion: 'submit'}, async ()=>{
            let list = [
              {label: '活动名称', name: 'activityName'},
              {label: '接收单位', name: 'acceptingUnit'},
              {label: '服务内容', name: 'serveTypeIds'},
              {label: '有效期开始时间', name: 'startingTime'},
              {label: '有效期结束时间', name: 'endTime'},
              {label: '券码', name: 'acddCardRollCodes'},
              {label: '商家列表', name: 'suitShopIds'},
            ]
            let errorRow = list.find(i => !row[i.name] || row[i.name] == '' || !row[i.name].length)
            if(errorRow){
              _self.$nextTick(() => {
                _self.$refs[`dialog-${ref}`].loading = false
              })
              return _self.$message.error(`${errorRow.label}不能为空`)
            }else{
              if(row.id){
                await editActivity(row).then(res => {
                  _self.$message.success(`修改成功`)
                  _self.$nextTick(() => {
                    _self.$refs[`dialog-${ref}`].showDialog = false
                  })
                  _self.$emit('submit', 'edit')
                })
              }else {
                await addActivity(row).then(res => {
                  _self.$message.success(`添加成功`)
                  _self.$nextTick(() => {
                    _self.$refs[`dialog-${ref}`].showDialog = false
                  })
                  _self.$emit('submit', 'add')
                })
              }
              _self.$nextTick(() => {
                _self.$refs[`dialog-${ref}`].loading = false
              })
            }
          }]
        ])
      }
      let actions = [...actionsMap()].filter(([key,value])=>(key.ref == ref && key.acion == acion))
      actions.forEach(([key,value])=>value.call(this))
    },
    showDialog(ref, type, row) {
      let _self = this;
      if (_self.$refs[`${ref}-form`]) {
        this.resetForm(`${ref}-form`);
      }
      _self.$nextTick(() => {
        _self.actionsMaps(ref, `${type}:show`, row)
      })
    },
    submitDialog(ref, row) {
      let _self = this;
      if(this.$refs[`${ref}-form`]){
        this.$refs[`${ref}-form`].validate((valid) => {
          if (valid) {
            _self.$refs[`dialog-${ref}`].loading = true
            _self.actionsMaps(ref, `submit`, row)
          } else {
            _self.$refs[`dialog-${ref}`].loading = false;
            return false;
          }
        });
      }else{
        _self.$refs[`dialog-${ref}`].loading = true
        _self.actionsMaps(ref, `submit`, row)
      }
    },
    async activeTypeChange(){
      let _self = this
      let { serveTypeTwo } = _self.currentItem
      await _self.queryServeList()
      getActiveFiles(serveTypeTwo).then(res => {
        _self.activeFiles = res.data
      })
    },
    packageChange(params){
      let _self = this
      _self.currentItem = {..._self.currentItem, ...params}
    },
    dataChange(params){
      let _self = this
      _self.currentItem = {..._self.currentItem, ...params}
    },
    ticketChange(list){
      let _self = this
      _self.$set(_self.currentItem, 'acddCardRollCodes', list.map(i => {
        return {cardRollCode: i.cardRollCode}
      }))
    }
  }
};
</script>
<style scoped lang="scss">
.form-content ::v-deep{
  .form-title{
    margin-bottom: vh(20);
    line-height: vh(34);
    font-size: vh(16);
    color: #0003AA;
  }
  .num-form-content{
    .num-desc-txt{
      font-size: 13px;
      color: #3D3D3D;
    }
    .num-form{
      width: vw(200);
      margin: 0 vw(20);
    }
    .num-btn{
      line-height: normal;
      margin-left: vw(20);
      .btn-txt{
        font-size: vh(13);
      }
    }
  }
}
</style>